package com.bra.ui.activity;

import java.util.HashMap;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import com.bra.bean.WeixinPay;
import com.bra.ui.base.BaseActivity;
import com.bra.utils.Contacts;
import com.bra.zhifubao.PayResult;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

/**
 * 订单支付界面(支付宝和微信)
 * 
 * @author lenovo
 */
public class Order_Activity extends BaseActivity {

	private IWXAPI api;
	private PayReq req;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Contacts.pay_zhifubao: {
				PayResult payResult = new PayResult((String) msg.obj);

				// 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
				String resultInfo = payResult.getResult();

				String resultStatus = payResult.getResultStatus();

				// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
				if (TextUtils.equals(resultStatus, "9000")) {
					Toast.makeText(Order_Activity.this, "支付成功",
							Toast.LENGTH_SHORT).show();
				} else {
					// 判断resultStatus 为非“9000”则代表可能支付失败
					// “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {
						Toast.makeText(Order_Activity.this, "支付结果确认中",
								Toast.LENGTH_SHORT).show();

					} else {
						// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
						Toast.makeText(Order_Activity.this, "支付失败",
								Toast.LENGTH_SHORT).show();

					}
				}
				break;
			}
			default:
				break;
			}
		};
	};

	@Override
	protected View onCreateView(LayoutInflater inflater,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void onViewCreated(Bundle savedInstanceState) {
		api = WXAPIFactory.createWXAPI(this, Contacts.APP_ID, true);
		api.registerApp(Contacts.APP_ID);

	}

	@Override
	protected void setListener() {
		// TODO Auto-generated method stub

	}

	// 微信支付
	protected void weiXinPay(String order_name, double ne_price) {
		HashMap<String, String> money_wei = new HashMap<String, String>();
		money_wei.put("money", ne_price + "");
		money_wei.put("order_nums", "订单编号");
		Toast.makeText(this, "获取订单中...", Toast.LENGTH_SHORT).show();
	}

	// 这些数据来自后台
	public void genPayReq(WeixinPay weixin) {
		if (weixin != null) {
			req.appId = weixin.appid;
			req.partnerId = weixin.partnerid;
			req.prepayId = weixin.prepayid;
			req.packageValue = weixin.package_value;
			req.nonceStr = weixin.noncestr;
			req.timeStamp = weixin.timestamp;
			req.sign = weixin.sign;
			api.registerApp(weixin.appid);
			api.sendReq(req);
		} else {
			Toast.makeText(this, "支付失败", 0).show();
		}

	}
}
